package com.app.couponsharelife.ui.main.me.order

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.OrderClassBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.TaobaoOrderBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.main.home.shopweb.TaoBaoWebActivity
import com.app.couponsharelife.utils.AppUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_selforder.*
import kotlinx.android.synthetic.main.rvitem_selforder.view.*

/**
 *Created by xct on 2019/4/8
 *Description:自营订单页面
 */
class SelfOrderFragment:LazyFragment() {
    private var animationDrawable:AnimationDrawable?=null
    private var orderClassBean:OrderClassBean?=null
    private var myAdapter: MyAdapter?=null
    private var pageIndex=1
    private var orderList= arrayListOf<TaobaoOrderBean.RowsBean>()
    companion object {
        fun newInstance(orderClassBean: OrderClassBean): SelfOrderFragment {
            val fragment = SelfOrderFragment()
            val bundle= Bundle()
            bundle.putParcelable("Data",orderClassBean)
            fragment.arguments =bundle
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_selforder

    override fun initViews() {
        orderClassBean=arguments!!.getParcelable("Data")
        setRefresh()
        myAdapter=MyAdapter()
        selfOrder_rv.layoutManager= LinearLayoutManager(activity)
        selfOrder_rv.adapter=myAdapter
    }
    @Subscribe(thread = EventThread.MAIN_THREAD, tags = [(Tag("selfOrder_RefreshData"))])
    fun receiveData(fresh: String) {
        pageIndex=1
        getGoodsList(false)
    }
    override fun lazyLoad() {
        getGoodsList(false)
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        selfOrder_smart.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable!!.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable!!.stop()
            }

            override fun loadMore() {
                getGoodsList(false)
            }

            override fun refresh() {
                pageIndex=1
                getGoodsList(true)
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }

    private fun getGoodsList(isRefresh:Boolean){
        if (!isRefresh&&pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map=HashMap<String,String>()
        map["pageNo"]=pageIndex.toString()
        map["pageSize"]="10"
        map["userId"]= AppUtils.getString(Contacts.USERID,"")
        map["platform"]=orderClassBean!!.type
        RetrofitWorker.retrofitWorker.getOrderList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<TaobaoOrderBean>>(){
                    override fun onComplete() {

                    }
                    override fun onNext(it: RemoteResultBean<TaobaoOrderBean>) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (it.data!=null&&it.data!!.records.isNotEmpty()){
                            if (pageIndex==1){
                                orderList.clear()
                                if (isRefresh){
                                    selfOrder_llerror.visibility= View.GONE
                                    selfOrder_rv.visibility= View.VISIBLE
                                    selfOrder_smart.finishRefresh()
                                }
                            }else{
                                selfOrder_smart.finishLoadMore()
                            }
                            orderList.addAll(it.data!!.records)
                            if (it.data!!.records.size<10){
                                selfOrder_smart.finishLoadMoreWithNoMoreData()
                            }
                            pageIndex++
                            myAdapter!!.notifyDataSetChanged()
                        }else{
                            if (isRefresh){
                                selfOrder_smart.finishRefresh()
                            }
                            if (pageIndex==1&&orderList.size==0){
                                selfOrder_smart.finishLoadMoreWithNoMoreData()
                                selfOrder_llerror.visibility= View.VISIBLE
                                selfOrder_rv.visibility= View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            selfOrder_smart.finishRefresh()
                        }
                        if (pageIndex>1){
                            selfOrder_smart.finishLoadMore()
                        }
                        if (pageIndex==1){
                            selfOrder_smart.finishLoadMoreWithNoMoreData()
                            selfOrder_llerror.visibility= View.VISIBLE
                            selfOrder_rv.visibility= View.GONE
                        }
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                            //Log.e("eeee","----->"+e.toString())
                        }
                    }

                })
    }
    private fun copyInviteCode(code: String) {
        //获取剪贴板管理器：
        val cm = context!!.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        val mClipData = ClipData.newPlainText("Label", code)
        // 将ClipData内容放到系统剪贴板里。
        cm.primaryClip = mClipData
        showToastMsg("复制成功！")
    }
    private inner class MyAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.rvitem_selforder,parent,false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return orderList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (orderList.size>0){
                if (holder is MyHolder){
                    val rowsBean=orderList[position]
                    val orderNum=rowsBean.ordersn?:""
                    Glide.with(holder.itemView.context)
                            .asBitmap()
                            .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                            .load(Contacts.REMOTE_IMAGE_URL +rowsBean.itemurl)
                            .into(holder.ivGoods!!)
                    holder.tvName?.text="      "+rowsBean.title
                    holder.tvOrderCode?.text="订单号   "+orderNum
                    holder.tvTime?.text="创建时间："+rowsBean.createTime
                    holder.tvPrice?.text=rowsBean.price+"元"
                    var wlCode=""
                    /*if (rowsBean.logisInforma==null||rowsBean.logisInforma!!.isEmpty()){
                        holder.clWl!!.visibility=View.GONE
                        holder.clAddress!!.visibility=View.VISIBLE
                    }else{
                        holder.clWl!!.visibility=View.VISIBLE
                        holder.clAddress!!.visibility=View.GONE
                        holder.tvWlCode!!.text=rowsBean.logisInforma?:""
                        var aar=rowsBean.logisInforma?.split(" ")
                        if (aar!=null&&aar.size>1){
                            wlCode=aar[1]
                        }
                    }*/
                    val type=rowsBean.orderstatus?:""
                    var orderType=""
                    when(type){
                        "0"->{  //已付款，未完善地址
                            orderType="待发货"
                            holder.clWl!!.visibility=View.GONE
                            holder.clAddress!!.visibility=View.VISIBLE
                        }
                        "1"->{  //已付款，完善地址，未发货
                            orderType="待发货"
                            holder.clWl!!.visibility=View.GONE
                            holder.clAddress!!.visibility=View.GONE
                        }
                        "2"->{  //已发货
                            orderType="已发货"
                            holder.clWl!!.visibility=View.VISIBLE
                            holder.clAddress!!.visibility=View.GONE
                            holder.tvWlCode!!.text=rowsBean.logisInforma?:""
                            var aar=rowsBean.logisInforma?.split(" ")
                            if (aar!=null&&aar.size>1){
                                wlCode=aar[1]
                            }
                        }
                        "3"->{  //订单结束
                            orderType="订单完成"
                        }
                        else->{
                            orderType="待发货"
                        }
                    }
                    holder.tvOrderType!!.text=orderType
                    holder.clWl?.setOnClickListener {
                        copyInviteCode(wlCode)
                    }
                    holder.clAddress?.setOnClickListener {
                        if (orderNum.isEmpty()){
                            showToastMsg("订单号错误，请稍后再试！")
                        }else {
                            //AppUtils.setString("SXPay","true")
                            val url = "http://www.yiyepay.cn/buyMember/address.html?openTime=${System.currentTimeMillis()}&userId=${AppUtils.getString(Contacts.USERID, "")}&isShowAlert=false&orderNum=$orderNum"
                            val intent = Intent(context, TaoBaoWebActivity::class.java)
                            intent.putExtra("url", url)
                            intent.putExtra("source", "SelfOrderFragment")
                            intent.putExtra("name", "完善收货地址")
                            startActivity(intent)
                        }
                    }
                }
            }
        }
    }
    private inner class MyHolder(itemview:View):RecyclerView.ViewHolder(itemview){
        var tvOrderCode:TextView?=null
        var tvOrderType:TextView?=null
        var ivGoods:ImageView?=null
        var tvName:TextView?=null
        var tvTime:TextView?=null
        var tvPrice:TextView?=null
        var tvWlCode:TextView?=null
        var clWl:ConstraintLayout?=null
        var clAddress:ConstraintLayout?=null
        init {
            tvOrderCode=itemview.selfOrder_rvitem_ddh
            tvName=itemview.selfOrder_rvitem_title
            tvOrderType=itemview.selfOrder_rvitem_ddtype
            tvPrice=itemview.selfOrder_rvitem_orderprice
            tvTime=itemview.selfOrder_rvitem_ordertime
            tvWlCode=itemview.selfOrder_tvWlCode
            ivGoods=itemview.selfOrder_rvitem_goodsimg
            clWl=itemview.selfOrder_clWl
            clAddress=itemview.selfOrder_clAddress
        }
    }
}